package com.ray.woodencreate.config;

import com.ray.woodencreate.data.MyStringArgumentResolver;
import com.ray.woodencreate.interceptor.AuthInterceptor;
import com.ray.woodencreate.logs.SystemLogBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author bo shen
 * @Description: 通用全局配置
 * @Class: MvcConfig
 * @Package com.toptoday.woodencreate.config
 * @date 2018/10/24 10:14
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class MvcConfig implements WebMvcConfigurer {

    @Value("${fw.excludePatterns}")
    private String excludePatterns;
    @Value("${fw.pathPatterns:/**}")
    private String pathPatterns;
    @Autowired
    private SysFileConfig sysFileConfig;

    /**
     * 日志拦截器
     */
    @Autowired
    private AuthInterceptor authInterceptor;


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
        /*放行swagger*/
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

        registry.addResourceHandler("/file/**")
                .addResourceLocations("file:"+sysFileConfig.getDir());

    }


    /**
     * 重写添加拦截器方法并添加配置拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(authInterceptor).addPathPatterns(pathPatterns);
        //配置过滤路径
        if (!StringUtils.isEmpty(excludePatterns)) {
            log.info(new SystemLogBuilder().appendLevelTips().appendMsg(excludePatterns).bulidString());
            interceptorRegistration.excludePathPatterns(excludePatterns.split(","));
        }
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new MyStringArgumentResolver());
    }
}
